import React from 'react'
// 注意，使用工具 classnames 来进行类名的添加，更为方便
import classNames from 'classnames'

// 定义 Button 的 size 和 type
export enum ButtonSize {
  large = 'lg',
  small = 'sm'
}

export enum ButtonType {
  Primary = 'primary',
  Default = 'default',
  Danger = 'danger',
  Link = 'link'
}

// 约束 props
interface BaseButtonProps {
  className?: string
  disbaled?: boolean
  size?: ButtonSize
  btnType?: ButtonType
  children: React.ReactNode
  href?: string
}

// 需要添加原生的button属性, 以便于添加 onClick 等事件
type NativeButtonProps = BaseButtonProps & React.ButtonHTMLAttributes<HTMLElement>
type AnchorButtonProps = BaseButtonProps & React.AnchorHTMLAttributes<HTMLElement>
export type ButtonProps = Partial<NativeButtonProps & AnchorButtonProps>

const Button: React.FC<ButtonProps> = (props) => {
  // restProps 表示用户可能传入的其余的属性
  const { btnType, className, disbaled, size, children, href, ...restProps } = props

  // 创建 class
  // 注意，只有 LinkedButton 才需要考虑添加 disabled 类，button 本身就有 disabled 属性
  const classes = classNames('btn', className, {
    [`btn-${btnType}`]: btnType,
    [`btn-${size}`]: size,
    disabled: btnType === ButtonType.Link && disbaled
  })

  if (btnType === ButtonType.Link && href) {
    return (
      <a className={classes} href={href} {...restProps}>
        {children}
      </a>
    )
  } else {
    return (
      <button className={classes} disabled={disbaled} {...restProps}>
        {children}
      </button>
    )
  }
}

Button.defaultProps = {
  disbaled: false,
  btnType: ButtonType.Default
}

export default Button
